package com.douma.service.impl;

import com.douma.dao.CommentDao;
import com.douma.dao.ShopDao;
import com.douma.dto.Comment;
import com.douma.dto.Shop;
import com.douma.service.ShopService;
import com.douma.utils.RedisConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


/**
 * 抖码课堂，专注中国程序员基础内功修炼
 * 官网：douma-tech.com
 * 公众号：抖码课堂
 *
 * @作者 : 老汤
 */

@Service("ShopServiceImpl_Hash")
public class ShopServiceImpl_Hash implements ShopService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Shop findById(Long id) {
        logger.info("开始【业务】查询商铺，商铺 id 为：" + id);
        // 1. 先从 Redis 缓存查询
        String key = RedisConstants.SHOP_KEY + id;
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
        if (map != null && !map.isEmpty()) {
            logger.info("【业务】查询商铺结束，从缓存 Redis 中返回数据");
            return Shop.buildFromMap(map);
        }
        // 2. 从数据库中去拿商铺数据
        Shop shop = shopDao.queryById(id);
        if (shop == null) return null;

        // 3. 将数据设置到 Redis 缓存
        stringRedisTemplate.opsForHash().putAll(key, shop.genMap());
        logger.info("【业务】查询商铺结束，商铺 id 为：" + id);
        return shop;
    }

    @Override
    @Transactional
    public void comment(Comment comment) {
        // 1. 将商铺表中的评论数增加 1
        shopDao.incCommentsById(comment.getShopId());
        // 2. 将评论插入到评论表中
        commentDao.insert(comment);
    }

    @Override
    public Long addShop(Shop shop) {
        return shopDao.insert(shop);
    }
}